package com.example.keepserver.service.impl;

import com.example.keepserver.dto.AuthResponse;
import com.example.keepserver.dto.LoginRequest;
import com.example.keepserver.dto.RegisterRequest;
import com.example.keepserver.dto.UserDTO;
import com.example.keepserver.model.User;
import com.example.keepserver.repository.UserRepository;
import com.example.keepserver.service.AuthService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Optional;
import java.util.UUID;

@Service
@RequiredArgsConstructor
public class AuthServiceImpl implements AuthService {
    
    // 依赖注入用户仓库
    private final UserRepository userRepository;
    
    @Override
    public AuthResponse login(LoginRequest request) {
        String username = request.getUsername();
        String password = request.getPassword();
        // 首先尝试通过昵称（用作用户名）查找用户
        Optional<User> userOpt = userRepository.findByUserId(username);
        // 如果没找到，尝试通过邮箱查找
        if (!userOpt.isPresent() && username.contains("@")) {
            userOpt = userRepository.findByEmail(username);
        }
        if (userOpt.isPresent()) {
            User user = userOpt.get();
            // 简单密码验证，实际项目中应使用加密
            if (password.equals(user.getPassword())) {
                UserDTO userDTO = UserDTO.builder()
                    .username(user.getNickname())
                    .email(user.getEmail())
                    .nickname(user.getNickname())
                    .avatarUrl(user.getAvatarUrl())
                    .gender(user.getGender())
                    .location(user.getLocation())
                    .followerCount(user.getFollowerCount())
                    .followingCount(user.getFollowingCount())
                    .postCount(user.getPostCount())
                    .createdAt(user.getCreatedAt())
                    .token(generateToken())
                    .build();
                
                return AuthResponse.success(userDTO, "登录成功");
            } else {
                return AuthResponse.error("密码错误");
            }
        } else {
            return AuthResponse.error("用户名不存在");
        }
    }
    
    @Override
    public AuthResponse register(RegisterRequest request) {
        String username = request.getUsername();
        String email = request.getEmail();
        String password = request.getPassword();
        
        // 检查用户名是否已存在
        if (userRepository.existsByNickname(username)) {
            return AuthResponse.error("用户名已存在");
        }
        
        // 检查邮箱是否已存在（如果提供了邮箱）
        if (email != null && !email.isEmpty() && userRepository.existsByEmail(email)) {
            return AuthResponse.error("邮箱已被注册");
        }
        
        // 创建新用户
        User newUser = new User();
        newUser.setUserId(generateUserId());
        newUser.setNickname(username);
        newUser.setEmail(email);
        newUser.setPassword(password);  // 实际项目中应加密存储密码
        newUser.setCreatedAt(LocalDateTime.now());
        newUser.setFollowerCount(0);
        newUser.setFollowingCount(0);
        newUser.setPostCount(0);
        // 保存用户
        User savedUser = userRepository.save(newUser);
        // 构建响应
        UserDTO userDTO = UserDTO.builder()
            .username(savedUser.getNickname())
            .email(savedUser.getEmail())
            .nickname(savedUser.getNickname())
            .gender(savedUser.getGender())
            .location(savedUser.getLocation())
            .followerCount(savedUser.getFollowerCount())
            .followingCount(savedUser.getFollowingCount())
            .postCount(savedUser.getPostCount())
            .createdAt(savedUser.getCreatedAt())
            .token(generateToken())
            .build();
        
        return AuthResponse.success(userDTO, "注册成功");
    }
    
    @Override
    public AuthResponse logout(String token) {
        // 实际项目中，这里应该将token加入黑名单或从存储中删除
        // 由于我们使用的是简单的模拟令牌，这里只需返回成功响应
        return AuthResponse.builder()
                .success(true)
                .message("退出登录成功")
                .build();
    }
    
    /**
     * 生成随机用户ID
     * @return 用户ID
     */
    private String generateUserId() {
        return "user" + System.currentTimeMillis() % 10000;
    }
    
    /**
     * 生成认证令牌，实际项目中应使用JWT等
     * @return 令牌
     */
    private String generateToken() {
        return "mock-token-" + UUID.randomUUID().toString();
    }
} 